const path = require('path');
const Koa = require('koa');
const serve = require('koa-static');
const helmet = require('koa-helmet');
const Router = require('koa-router');
// const koaWebpack = require('koa-webpack');

// const webpackDev = require('../../config/webpack.dev');
// const webpackProd = require('../../config/webpack.prod');

const AppSSR = require('../../build/node/ssr.bundle');

const appSSR = new AppSSR();

// const dev = process.env.NODE_ENV !== 'production';

const router = new Router();

router.get('*', async (ctx) => {
  const rendered = appSSR.render(ctx.url);
  ctx.body = `
     <!DOCTYPE html>
       <html lang="en">
       <head>
         <meta charset="UTF-8">
         <title>React SSR</title>
       </head>
       <body>
        <div id="root">${rendered.html}</div>
        ${rendered.scripts.join()}
        <script type="text/javascript" src="/client.bundle.js"></script>
       </body>
     </html>
   `;
});

const server = new Koa();

// koaWebpack({ config: dev ? webpackDev : webpackProd })
//   .then(middleware => {
//     server.use(middleware);
//   });


server
  .use(helmet())
  // .use(serve(path.resolve(__dirname, '/public')))
  .use(serve(path.resolve(__dirname, '../../build')))
  .use(router.routes())
  .use(router.allowedMethods());

const port = process.env.PORT || 3000;
AppSSR.preloadAll().then(() => {
  server.listen(process.env.PORT || 3000, (error) => {
    if (error) {
      console.log(error);
    }
  
    console.log(`> Ready on http://localhost:${port}`);
    console.log('🚀 started');
  });
});
